<?php


namespace app\admin\service\curd;


use app\admin\model\system\SystemGenTableColumn;
use app\admin\service\curd\exceptions\TableException;
use think\facade\Db;
use think\helper\Str;

class GenService extends BuildCurdService
{
    /**
     * 设置主表
     * @param $row
     * @return $this
     * @throws TableException
     */
    public function setTable($table)
    {
        $this->table = str_replace($this->tablePrefix, '', $table->table_name);
        try {

            // 获取表列注释
            $colums = SystemGenTableColumn::where('table_id', $table->id)->select();

            foreach ($colums as $vo) {
                $colum = [
                    'type' => $vo['column_type'],
                    'comment' => $vo['column_comment'],
                    'required' => $vo['is_required'] ? true : false,
                    'default' => '',
                    'field' => $vo['column_name'],
                    'is_list' => $vo['is_list'],
                    'is_query' => $vo['is_query'],
                    'is_insert' => $vo['is_insert'],
                    'is_edit' => $vo['is_edit'],
                ];
                $colum['comment'] .= '{'.$vo['html_type'].'}';
                if ($vo['dict_type']) $colum['comment'] .= "({$vo['dict_type']})";

                // 格式化列数据
                $this->buildColum($colum);

                $this->tableColumns[$vo['column_name']] = $colum;

                if ($vo['column_name'] == 'delete_time') {
                    $this->delete = true;
                }
            }

            // 获取表名注释
            $this->tableComment = $table->table_comment;
        } catch (\Exception $e) {
            throw new TableException($e->getMessage());
        }


        $this->controllerFilename = $this->getTableControllerName($this->table);

        // 初始化默认模型名
        $this->modelFilename = Str::studly($this->table);

        $this->buildViewJsUrl();

        // 构建数据
        $this->buildStructure();

        return $this;
    }

    /**
     * 构建初始化字段信息
     * @param $colum
     * @return mixed
     */
    public function buildColum(&$colum)
    {
        parent::buildColum($colum);
        return $colum;
    }
}